package cn.onein.edu.backend.job;

import java.util.List;

import org.apache.log4j.Logger;

import cn.onein.edu.backend.service.DailyUserActionsService;
import cn.onein.edu.biz.bean.User;
import cn.onein.edu.common.MailType;
import cn.onein.edu.util.ResourceUtil;

/**
 * 用户每日行动指南数据处理以及邮件发送的JOB
 * @author Upton
 *
 */
public class DailyUserActionsJob extends BaseJob{
	Logger logger = Logger.getLogger(DailyUserActionsJob.class);
	
	//每个事务处理的最大数据量
	private final static int MAX_PROCESS_PRE_TA = 100;
	
	private DailyUserActionsService dailyUserActionsService;
	
	public void setDailyUserActionsService(DailyUserActionsService dailyUserActionsService){
		this.dailyUserActionsService = dailyUserActionsService;
	}
	
	@Override
	public void start() {
		logger.info("DailyUserActionsJob start");
		//发送开始邮件
		String userEmail = ResourceUtil.getJobMonitorMailProperties().getString("MAIN_MONITOR_MAIL");
		getSendMailProducer().sendJobMailMessage(MailType.JobStart, JobType.DailyUserActionsJob, userEmail);
		
		int allPreccessedNum = 0;
		String message = "已经处理的用户数：";
		try{
			//初始化
			dailyUserActionsService.initUserShadow();
			
			//开始处理
			int precessedNum = 0; 
			List<User> list = dailyUserActionsService.doDailyUserActions(MAX_PROCESS_PRE_TA);
			
			if(list != null && list.size() > 0){
				precessedNum = list.size();
				//发送每日邮件
				sendDailyActionMail(list);
			}
			else{
				precessedNum = 0;
			}
			
			while(precessedNum > 0){
				allPreccessedNum += precessedNum;
				
				list = dailyUserActionsService.doDailyUserActions(MAX_PROCESS_PRE_TA);
				
				if(list != null && list.size() > 0){
					precessedNum = list.size();
					//发送每日邮件
					sendDailyActionMail(list);
				}
				else{
					precessedNum = 0;
				}
			}
			
			logger.info("DailyUserActionsJob end. All preccessed number:" + allPreccessedNum);
			//发送结束邮件
			message = message + allPreccessedNum;
			getSendMailProducer().sendJobMailMessage(MailType.JobEnd, JobType.DailyUserActionsJob, userEmail, message);
		}
		catch(Exception ex){
			logger.error("DailyUserActionsJob error",ex);
			//发送出错邮件
			message = message + allPreccessedNum;
			getSendMailProducer().sendJobMailMessage(MailType.JobError, JobType.DailyUserActionsJob, userEmail, message);
		}
	}
	
	private void sendDailyActionMail(List<User> list){
		// 发送每日邮件
		for(User user : list){
			getSendMailProducer().sendDailyMailMessage(user);
		}
	}
}
